package com.djq.hhc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djq.hhc.dataprocess.ImgLoadUtils;
import com.djq.hhc.dto.UserInfoDto;
import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.model.post.PostInfo;
import com.djq.hhc.model.user.UserInfo;
import com.djq.hhc.result.Result;
import com.djq.hhc.service.PostInfoService;
import com.djq.hhc.vo.PostInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/03/02/下午 4:45
 * @Description:
 */

@RestController
@RequestMapping(value = "/post/postInfo")
public class PostInfoController {

    @Autowired
    private PostInfoService postInfoService;

    //点赞排行
    //点赞
    @GetMapping("/likesRank/{id}")
    public Result LikesRank(@RequestHeader("Authorization") String token, @PathVariable("id") Long id) {
        return postInfoService.getLikesRank(token, id);
    }

    //点赞
    @GetMapping("/likes/{id}")
    public Result Likes(@PathVariable("id") Long id) {
        return postInfoService.likePost(id);
    }

    //发表帖子
    @PostMapping("post")
    public Result saveBlog(@RequestBody PostInfo postInfo) {
        //获取登录用户
        UserInfoDto user = UserHolder.getUser();
        if (user == null) {
            return Result.fail().message("请先登录");
        }
        //保存帖子
        if (StringUtils.isEmpty(postInfo.getTitle()) || postInfo.getTitle() == null) {
            return Result.fail().message("标题不能为空");
        }
        if (StringUtils.isEmpty(postInfo.getPic()) || postInfo.getPic() == null) {
            return Result.fail().message("图片不能为空");
        }
        if (StringUtils.isEmpty(postInfo.getText()) || postInfo.getText() == null) {
            return Result.fail().message("内容不能为空");
        }
        if (postInfo.getType() == null) {
            return Result.fail().message("类别不能为空");
        }
        postInfo.setUserId(user.getId());
        postInfoService.save(postInfo);
        //返回id
        return Result.ok(postInfo.getId()).message("发表成功");
    }

    //通过id获取帖子
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        PostInfo postInfo = postInfoService.getById(id);
        if (id == null) {
            return Result.fail().message("帖子不存在");
        }
        //添加喜欢
        postInfoService.isPostLiked(postInfo);
        return Result.ok(postInfo);
    }

    //删除帖子
    @DeleteMapping("remove/{id}")
    public Result removeById(@PathVariable Integer id) {
        Boolean isOk = postInfoService.removeById(id);
        if (isOk) {
            return Result.ok(null).message("删除帖子成功");
        } else {
            return Result.fail(null).message("删除帖子失败");
        }
    }

    //修改
    @PutMapping("update")
    public Result updateById(@RequestBody PostInfo postInfo) {
        if (StringUtils.isEmpty(postInfo.getTitle()) || postInfo.getTitle() == null) {
            return Result.fail().message("标题不能为空");
        }
        if (StringUtils.isEmpty(postInfo.getPic()) || postInfo.getPic() == null) {
            return Result.fail().message("图片不能为空");
        }
        if (StringUtils.isEmpty(postInfo.getText()) || postInfo.getText() == null) {
            return Result.fail().message("内容不能为空");
        }
        if (postInfo.getType() == null) {
            return Result.fail().message("类别不能为空");
        }
        return postInfoService.updateUserById(postInfo);
    }

    //获取全部
    @GetMapping("getAllPost")
    public Result getAllPost(@RequestParam(required = false) Long type) {
        QueryWrapper<PostInfo> wrapper = new QueryWrapper<>();
        if (type != null) {
            wrapper.eq("type",type);
        }
        List<PostInfo> list = postInfoService.list(wrapper);
        list.forEach(post -> {
            postInfoService.isPostLiked(post);
        });
        return Result.ok(list);
    }

    //分页前端
    @PostMapping("myPostPage/{page}/{limit}")
    public Result myPostPage(
            @PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody(required = false) PostInfoVo postInfoVo) {
        UserInfoDto user = UserHolder.getUser();
        if (user == null) {
            return Result.fail().message("请先登录");
        }
        //创建page对象，传递当前页和每页记录数
        Page<PostInfo> pageParam = new Page<>(page, limit);
        //获取条件值
        String text = postInfoVo.getText(); //模糊查询，标题和内容，就用这个代替了
        Long type = postInfoVo.getType();
        //封装条件
        QueryWrapper<PostInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getId());
        if(!StringUtils.isEmpty(text)) {
            wrapper.like("text",text).or(); //模糊内容
            wrapper.like("title", text).or(); //模糊标题
        }
        if(!StringUtils.isEmpty(type)) {
            wrapper.eq("type",type);
        }
        wrapper.orderByDesc("create_time");
        //调用方法得到分页查询结果
        IPage<PostInfo> pageModel = postInfoService.page(pageParam, wrapper);
        List<PostInfo> records = pageModel.getRecords();
        records.forEach(post -> {
            postInfoService.isPostLiked(post);
        });
        return Result.ok(pageModel);
    }

    //分页前端
    @PostMapping("pageWithLike/{page}/{limit}")
    public Result indexWithLike(
            @PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody(required = false) PostInfoVo postInfoVo) {
        //创建page对象，传递当前页和每页记录数
        Page<PostInfo> pageParam = new Page<>(page, limit);
        //获取条件值
        String title = postInfoVo.getTitle();
        String text = postInfoVo.getText();
        Long type = postInfoVo.getType();
        Long userId = postInfoVo.getUserId();
        //封装条件
        QueryWrapper<PostInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(title)) {
            wrapper.like("title",title);
        }
        if(!StringUtils.isEmpty(text)) {
            wrapper.like("text",text);
        }
        if(!StringUtils.isEmpty(type)) {
            wrapper.eq("type",type);
        }
        if(!StringUtils.isEmpty(userId)) {
            wrapper.like("user_Id",userId);
        }
        wrapper.orderByDesc("create_time");
        //调用方法得到分页查询结果
        IPage<PostInfo> pageModel = postInfoService.page(pageParam, wrapper);
        List<PostInfo> records = pageModel.getRecords();
        records.forEach(post -> {
            postInfoService.isPostLiked(post);
        });
        return Result.ok(pageModel);
    }

    //分页后端
    @PostMapping("{page}/{limit}")
    public Result index(
            @PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody(required = false) PostInfoVo postInfoVo) {
        //创建page对象，传递当前页和每页记录数
        Page<PostInfo> pageParam = new Page<>(page, limit);
        //获取条件值
        String title = postInfoVo.getTitle();
        String text = postInfoVo.getText();
        Long type = postInfoVo.getType();
        Long userId = postInfoVo.getUserId();
        //封装条件
        QueryWrapper<PostInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(title)) {
            wrapper.like("title",title);
        }
        if(!StringUtils.isEmpty(text)) {
            wrapper.like("text",text);
        }
        if(!StringUtils.isEmpty(type)) {
            wrapper.eq("type",type);
        }
        if(!StringUtils.isEmpty(userId)) {
            wrapper.like("user_Id",userId);
        }
        wrapper.orderByDesc("create_time");
        //调用方法得到分页查询结果
        IPage<PostInfo> pageModel = postInfoService.page(pageParam, wrapper);
        List<PostInfo> records = pageModel.getRecords();
        records.forEach(post -> {
            postInfoService.isPostLiked(post);
        });
        return Result.ok(pageModel);
    }

    /**
     * 下载图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        String s = ImgLoadUtils.upLoad(file);
        return Result.ok(s);
    }

    /**
     * 下载图片
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        ImgLoadUtils.downLoad(name, response);
    }
}
